package com.example.demo;

import org.junit.jupiter.api.Test;

import java.sql.*;

public class JdbcTest {
    void test2() throws SQLException, ClassNotFoundException {
        /*this.save("xxy","19021193",22);*/
        this.get2("zs");
    }

    private void  save(String name,String idno, int age){
        String sql="INSERT INTO t_student(name,idno,age) VALUES ('"+name+"','"+idno+"',"+age+")";
    }
    @Test
    private void get2(String queryName ) throws ClassNotFoundException,SQLException{
        String sql="SELECT * FROM t_student WHERE name=?";
        System.out.println("sql:"+sql);
        String URL="jdbc:mysql://192.168.80.64:3306/soft_test?characterEncoding=utf-8";
        String USER="root";
        String PASSWORD="123456";
        Class.forName("com.mysql.jdbc.Driver");
        try (Connection conn= DriverManager.getConnection(URL,USER,PASSWORD)) {
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setString(1, queryName);

            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                while (resultSet.next()) {
                    int id = resultSet.getInt("id");
                    String name = resultSet.getString("name");
                    String idno = resultSet.getString("idno");
                    int age = resultSet.getInt("age");
                    System.out.printf("id=%d,name=%s,idno=%s,age=%d\n", id, name, idno, age);
                }
            }
        }

    }

    @Test
    void test() throws ClassNotFoundException, SQLException{
        String URL="jdbc:mysql://192.168.80.64:3306/soft_test?characterEncoding=utf-8";
        String USER="root";
        String PASSWORD="123456";
        Class.forName("com.mysql.jdbc.Driver");
        try (Connection conn= DriverManager.getConnection(URL,USER,PASSWORD)){
            System.out.println(conn.isClosed());

            /*String sql="INSERT INTO t_student(name,idno,age) VALUES ('徐翔宇','190201193',22)";*/
            /* String sql="DELETE FROM t_student WHERE name='张三'";*/
            String sql="SELECT * FROM t_student";


            try (Statement statement=conn.createStatement()){
                boolean execute=statement.execute(sql);
                System.out.println(execute);
                statement.execute("UPDATE t_student SET name='updated' WHERE id = 2");
                try(ResultSet resultSet=statement.executeQuery("SELECT * FROM t_student")) {
                    while(resultSet.next()){
                        int id = resultSet.getInt("id");
                        String name = resultSet.getString("name");
                        String idno = resultSet.getString("idno");
                        int age = resultSet.getInt("age");
                        System.out.printf("id=%d,name=%s,idno=%s,age=%d\n",id,name,idno,age);
                    }
                }
            }



        }







    }
}
